package com.gcstorage.tvdev.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.gcstorage.tvdev.R
import com.gcstorage.tvdev.base.RxBaseActivity
import com.gcstorage.tvdev.constants.ARouterPaths
import com.gcstorage.tvdev.constants.AppConstant
import com.gcstorage.tvdev.constants.KeyCode
import com.gcstorage.tvdev.constants.LogCat
import com.gcstorage.tvdev.net.ApiAddress
import com.gcstorage.tvdev.net.HttpClient
import com.gcstorage.tvdev.net.RxObserver
import com.gcstorage.tvdev.util.JumpHelper
import com.gcstorage.tvdev.util.ResUtils
import com.gcstorage.tvdev.util.SpUtils
import com.gcstorage.tvdev.util.UserHelper
import com.google.gson.JsonElement
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * 欢迎界面
 * Created by zjs on 2018/10/29.
 */
class SplashActivity : RxBaseActivity() {
    //    private var hasFloatPermission = false
    override fun getLayoutId(): Int {
        return R.layout.splash_activity
    }

    override fun initView() {
        requestPermissions()
//        hasFloatPermission = FloatPermissionManager.isRequestFloatPermission(mActivity)
    }

    override fun initData() {
        SpUtils.putBoolean("isSplash", true)
        initMetaData()

//        ToastUtils.getDefaultMaker().setBgColor(resources.getColor(R.color.color_262D49))
//            .setGravity(
//                Gravity.CENTER, 0, 0
//            ).setTextColor(
//                resources.getColor(R.color.color_white)
//            )
//        nextPage()
    }

    //初始化meta数据
    private fun initMetaData() {
        if (SpUtils.getBoolean(KeyCode.CONFIG_MODE)) return  //ip配置模式
        SpUtils.putString(
            AppConstant.cityName,
            ResUtils.getMetaData(this, "cityName", "") as String
        )
        SpUtils.putString(
            AppConstant.cityHost,
            ResUtils.getMetaData(this, "cityHost", "") as String
        )
        SpUtils.putString(
            AppConstant.cityWebSocket,
            ResUtils.getMetaData(this, "cityWebSocket", "") as String
        )
        SpUtils.putString(
            AppConstant.map_box_url,
            ResUtils.getMetaData(this, "mapBoxUrl", "") as String
        )
        SpUtils.putString(
            AppConstant.tenantId,
            ResUtils.getMetaData(this, "tenantId", "").toString().replace("tenantId", "")
        )
        SpUtils.putString(
            AppConstant.clientId,
            ResUtils.getMetaData(this, "clientId", "") as String
        )
//        SpUtils.putFloat(KeyCode.LOCATION_DEFAULT_LNG, BuildConfig.defaultLongitude)
//        SpUtils.putFloat(KeyCode.LOCATION_DEFAULT_LAT, BuildConfig.defaultLatitude)
        // GcRetrofitManager.manager().initService(SpUtils.getString("cityHost"), GcApiService.class, Collections.singletonList(new GcHeaderInterceptor()));
    }

    @SuppressLint("CheckResult")
    private fun requestPermissions() {
        RxPermissions(this).request(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
//            Manifest.permission.BODY_SENSORS,
//            Manifest.permission.USE_FINGERPRINT,
//            Manifest.permission.CALL_PHONE,
//            Manifest.permission.RECORD_AUDIO,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.READ_CALL_LOG,
//            Manifest.permission.READ_PHONE_STATE,
            //TV端没有定位的权限
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { aBoolean ->
                if (aBoolean) {
                    nextPage()
                } else {
                    requestPermissions()
                    LogUtils.d(LogCat.LOG_COMMONON + " 请求权限requestPermissions----")
//                    ToastUtils.showShort("请去权限设置界面打开权限")
                }
            }
    }

    private fun nextPage() {
        val token = SpUtils.getString(SpUtils.TAG_USER, KeyCode.USER_ACCESS_TOKEN, "")
        val loginState = UserHelper.instance().loginStatus
        if (loginState && !TextUtils.isEmpty(token)) {
            checkToken(token)
        } else {
            gotoLogin()
        }
    }

    //校验token
    private fun checkToken(token: String) {
        val params = HashMap<String, Any>()
        params["token"] = token
        HttpClient.get().post(
            AppConstant.getApiAddress() + ApiAddress.AUTH_CHECK_TOKEN,
            params,
            object : RxObserver() {
                override fun onSuccess(t: JsonElement) {
                    LogUtils.d(LogCat.LOG_COMMONON+" 校验token ${t}")
                    SpUtils.putBoolean("isSplash", false)
                    UserHelper.instance().loginStatus = true
//                    JumpHelper.gotoMainActivity(mActivity)
                    ARouter.getInstance().build(ARouterPaths.TV_APP_MAIN).navigation()
                    finish()
                }

                override fun onFail() {
                    gotoLogin()
                }
            })
    }

    private fun gotoLogin() {
//        JumpHelper.gotoLoginActivity()
        val intent =Intent(this,TvLoginActivity::class.java)
        startActivity(intent)
        finish()
    }


    override fun onResume() {
        super.onResume()
//        nextPage()
//        requestPermissions()
    }

}